<template>
  <div class="dicom-viewer-container">
      <!-- 顶部操作工具栏 -->
      <div class="toolbar">

        <!-- 基本操作 -->
        <div class="toolbar-group">
          <span class="group-label">基本操作:</span>
          <el-button size="small" @click="flipHorizontal">
            <el-icon><Switch /></el-icon>
            镜像
          </el-button>
          <el-button size="small" @click="rotateClockwise">
            <el-icon><RefreshRight /></el-icon>
            旋转
          </el-button>
          <el-button size="small" @click="resetView">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>

        <!-- 调窗控制 -->
        <div class="toolbar-group">
          <span class="group-label">调窗:</span>
          <div class="windowing-controls">
            <div class="windowing-item">
              <span class="windowing-label">窗宽:</span>
              <el-slider
                v-model="windowWidth"
                :min="1"
                :max="4000"
                :step="1"
                @input="onWindowingChange"
                style="width: 120px;"
              />
              <span class="windowing-value">{{ windowWidth }}</span>
            </div>

            <div class="windowing-item">
              <span class="windowing-label">窗位:</span>
              <el-slider
                v-model="windowLevel"
                :min="-1000"
                :max="3000"
                :step="1"
                @input="onWindowingChange"
                style="width: 120px;"
              />
              <span class="windowing-value">{{ windowLevel }}</span>
            </div>
          </div>
        </div>



        <!-- 切片信息 -->
        <div class="toolbar-group">
          <span class="slice-info">{{ currentSliceIndex + 1 }} / {{ maxSliceIndex + 1 }}</span>
        </div>
      </div>
      
      <!-- DICOM图像显示区域 -->
      <div id="dicom-viewport" class="dicom-viewport"></div>
      
      <!-- 底部切片滑动条 -->
      <div class="slice-slider-container">
        <el-slider 
          v-model="currentSliceIndex" 
          :min="0" 
          :max="maxSliceIndex" 
          @input="onSliceChange"
          :show-tooltip="false"
        />
      </div>
    </div>

    <!-- imageLoaders组件 -->
    <imageLoaders 
      :study-id="props.studyId" 
      :study-uid="props.studyInstanceUid" 
      :series-uid="props.seriesInstanceUid"
      @series-loaded="onSeriesLoaded" 
    />
</template>

<script setup>
let activeRenderingEngines = new Set();

// 定义props
const props = defineProps({
  studyId: {
    type: Number,
    required: true
  },
  studyInstanceUid: {
    type: String,
    required: true
  },
  seriesInstanceUid: {
    type: String,
    required: true
  }
})

// 定义emits
const emit = defineEmits(['imagesLoaded', 'imageChange'])

import {
  ref,
  onMounted,
  onUnmounted,
  watch
} from "vue";
import {
  ElMessage
} from "element-plus";
import * as cornerstone from "@cornerstonejs/core";
import * as cornerstoneTools from "@cornerstonejs/tools";
import {
  ToolGroupManager,
  PanTool,
  ZoomTool,
  LengthTool,
  RectangleROITool,
  CrosshairsTool,
  Enums as csToolsEnums
} from "@cornerstonejs/tools";

import {
  Enums as csEnums,
  RenderingEngine,
  volumeLoader,
  imageLoader,
  getRenderingEngine,
  cache,
  metaData,
} from "@cornerstonejs/core";

import {
  initDemo,
  createImageIdsAndCacheMetaData,
  setTitleAndDescription,
} from "@/utils/dicom/utils.js";
import {
  dicomImageLoader,
  webImageLoader
} from "@/utils/dicom/cornerstoneImageLoader";

import {
  initProviders,
  initCornerstoneWADOImageLoader,
  initVolumeLoader,
  DicomDataService
} from "@/api/pacs/dicom/cornerstoneService";

import {
  IMAGE_LOADER_SCHEME,
  VOLUME_LOADER_SCHEME
} from "@/const/dicom";

import {
  getDicomImageId
} from "@/utils/dicom/dicom";
import {
  Switch,
  RefreshRight,
  Refresh,

} from "@element-plus/icons-vue";
import {
  useRoute
} from "vue-router";
import {
  MESSAGE_TYPE
} from "@/const/dicom";
import imageLoaders from "./imageLoaders.vue";

const TOOLS = {
  ZOOM: "Zoom",
  PAN: "Pan",
  MEASUREMENT: "Length",
  ROI: "RectangleROI",
  CROSSHAIRS: "Crosshairs",
  OVERLAY: "Overlay",
};

const route = useRoute();
const studyUid = ref(route.params.studyUid);
const seriesUid = ref(null);
let renderingEngine = null;// 响应式数据
const viewport = ref(null);
const currentSliceIndex = ref(0);
const maxSliceIndex = ref(0);
const overviewCanvasRef = ref(null);

// 新增调窗参数和初始值存储
const windowWidth = ref(400);
const windowLevel = ref(40);
const initialWindowWidth = ref(400);
const initialWindowLevel = ref(40);



onMounted(async () => {
  try {
    initCornerstone();
    initOverviewCanvas();
    onSeriesSelected(seriesUid);
    console.log('---DicomViewer组件挂载完成');
  } catch (error) {
    console.error('DicomViewer组件挂载失败:', error);
  }
});

/***
 *
 *  
**/
onUnmounted(() => {
  console.log("DicomViewer组件卸载，清理所有资源");
  
  // 清理所有渲染引擎
  for (const engineId of activeRenderingEngines) {
    try {
      const engine = getRenderingEngine(engineId);
      if (engine) {
        engine.destroy();
      }
    } catch (error) {
      console.warn("卸载时销毁渲染引擎失败:", engineId, error);
    }
  }
  activeRenderingEngines.clear();
  
  // 清理工具组
  try {
    const toolGroup = ToolGroupManager.getToolGroup('default');
    if (toolGroup) {
      ToolGroupManager.destroyToolGroup('default');
    }
  } catch (error) {
    console.warn("卸载时清理工具组失败:", error);
  }

});

watch(viewport, (newViewport) => {
  if (newViewport) {
    newViewport.element.addEventListener(
      csEnums.Events.CAMERA_MODIFIED,
      updateOverviewCanvas
    );
    newViewport.element.addEventListener(
      csEnums.Events.IMAGE_RENDERED,
      updateOverviewCanvas
    );
  }
});

function initCornerstone() {
  try {
    initProviders();
    initCornerstoneWADOImageLoader();
    initVolumeLoader();
    imageLoader.registerImageLoader(IMAGE_LOADER_SCHEME, dicomImageLoader);
    imageLoader.registerImageLoader("web", webImageLoader);
    
    // 初始化工具
    cornerstoneTools.init();
    
    // 先注册工具到库中
    cornerstoneTools.addTool(PanTool);
    cornerstoneTools.addTool(ZoomTool);
    cornerstoneTools.addTool(LengthTool);
    cornerstoneTools.addTool(RectangleROITool);
    cornerstoneTools.addTool(CrosshairsTool);
    
    // 检查工具组是否已存在，如果存在则销毁
    const existingToolGroup = ToolGroupManager.getToolGroup('default');
    if (existingToolGroup) {
      console.log('工具组已存在，正在销毁...');
      ToolGroupManager.destroyToolGroup('default');
    }
    
    // 创建工具组
    const toolGroup = ToolGroupManager.createToolGroup('default');
    
    if (!toolGroup) {
      console.error('工具组创建失败');
      return;
    }
    
    // 添加工具到工具组
    toolGroup.addTool(PanTool.toolName);
    toolGroup.addTool(ZoomTool.toolName);
    toolGroup.addTool(LengthTool.toolName);
    toolGroup.addTool(RectangleROITool.toolName);
    toolGroup.addTool(CrosshairsTool.toolName);
    
    // 设置默认工具状态 - 鼠标滚轮缩放，左键拖拽
    toolGroup.setToolActive(ZoomTool.toolName, {
      bindings: [
        {
          mouseButton: csToolsEnums.MouseBindings.Wheel,
        },
      ],
    });
    toolGroup.setToolActive(PanTool.toolName, {
      bindings: [
        {
          mouseButton: csToolsEnums.MouseBindings.Primary,
        },
      ],
    });
    
    console.log('DicomViewer Cornerstone初始化完成');
  } catch (error) {
    console.error('DicomViewer Cornerstone初始化失败:', error);
  }
}


async function onSeriesSelected(selectedSeriesUid) {
  console.log("==========================================================")
  seriesUid.value = selectedSeriesUid;
  await loadSeries(selectedSeriesUid);
}


/***
 * 价值
 */
async function loadSeries(seriesUid) {
  const series = await DicomDataService.getSeriesImages(studyUid.value, seriesUid);


  console.log("--输出从服务端返回的信息--");
  console.log(series);

  const imageIds = series.map((instance) => getDicomImageId(instance));
  await createImageIdsAndCacheMetaData({
    imageIds,
    StudyInstanceUID: studyUid.value,
    SeriesInstanceUID: seriesUid,
    SOPInstanceUID: series[0].SOPInstanceUID,
  });
  const renderingEngineId = "myRenderingEngine";
  const viewportId = "myViewport";
  //设置引擎
  renderingEngine = new RenderingEngine(renderingEngineId);
  const viewportInput = {
    viewportId,
    element: document.getElementById("dicom-viewport"),
    type: csEnums.ViewportType.STACK,
  };
  renderingEngine.enableElement(viewportInput);
  viewport.value = renderingEngine.getViewport(viewportId);
  
  // 将工具组绑定到视口
  const toolGroup = ToolGroupManager.getToolGroup('default');
  if (toolGroup) {
    toolGroup.addViewport(viewportId, renderingEngineId);
  }
  
  viewport.value.setStack(imageIds);
  maxSliceIndex.value = imageIds.length - 1;
  currentSliceIndex.value = 0;
  
  // 设置初始调窗参数
  const properties = viewport.value.getProperties();
  if (properties.voiRange) {
    windowWidth.value = Math.round(properties.voiRange.upper - properties.voiRange.lower);
    windowLevel.value = Math.round((properties.voiRange.upper + properties.voiRange.lower) / 2);
  }
  
  viewport.value.render();
  updateOverviewCanvas();
}

async function onSeriesLoaded(data) {
  console.log("DicomViewer接收到序列数据:", data);
  
  try {
    if (data && data.imageIds && data.imageIds.length > 0) {
      console.log("开始在DicomViewer中渲染图像...");
      
      // 确保DOM元素存在并有正确的尺寸
      const viewportElement = document.getElementById("dicom-viewport");
      if (!viewportElement) {
        console.error("找不到dicom-viewport元素");
        return;
      }

      // 确保视口元素有正确的尺寸
      if (viewportElement.clientWidth === 0 || viewportElement.clientHeight === 0) {
        console.warn("视口元素尺寸为0，强制设置尺寸");
        viewportElement.style.width = '800px';
        viewportElement.style.height = '600px';
      }

      console.log("视口元素尺寸:", {
        width: viewportElement.clientWidth,
        height: viewportElement.clientHeight
      });

      // 清理现有渲染引擎
      if (renderingEngine) {
        try {
          console.log("清理现有渲染引擎");
          renderingEngine.destroy();
        } catch (e) {
          console.warn("清理渲染引擎时出错:", e);
        }
        renderingEngine = null;
      }

      // 创建新的渲染引擎
      const renderingEngineId = "MAIN_VIEWER";
      renderingEngine = new RenderingEngine(renderingEngineId);

      // 启用视口
      const viewportId = "MAIN_VIEWPORT";
      const viewportInput = {
        viewportId,
        element: viewportElement,
        type: csEnums.ViewportType.STACK,
      };

      renderingEngine.enableElement(viewportInput);
      console.log("视口已启用");

      // 获取视口实例
      viewport.value = renderingEngine.getViewport(viewportId);
      console.log("视口实例获取成功");

      // 设置图像堆栈
      console.log("设置图像堆栈，图像数量:", data.imageIds.length);
      await viewport.value.setStack(data.imageIds);
      console.log("图像堆栈设置完成");

      // 设置初始图像索引
      viewport.value.setImageIdIndex(0);
      console.log("初始图像索引设置为0");

      // 获取工具组并添加视口
      const toolGroup = ToolGroupManager.getToolGroup('default');
      if (toolGroup) {
        toolGroup.addViewport(viewportId, renderingEngineId);
        console.log("工具组已添加到视口");
      }

      // 设置切片范围
      maxSliceIndex.value = data.imageIds.length - 1;
      currentSliceIndex.value = data.currentIndex || 0;
      console.log("切片范围设置完成:", { max: maxSliceIndex.value, current: currentSliceIndex.value });

      // 设置默认窗宽窗位
      setTimeout(() => {
        try {
          // 尝试从图像元数据获取窗宽窗位
          const currentImageId = data.imageIds[0];
          const voiLutModule = cornerstone.metaData.get('voiLutModule', currentImageId);
          
          let windowWidthValue = 400;
          let windowLevelValue = 40;
          
          if (voiLutModule && voiLutModule.windowWidth && voiLutModule.windowCenter) {
            windowWidthValue = voiLutModule.windowWidth;
            windowLevelValue = voiLutModule.windowCenter;
            console.log("使用DICOM元数据的窗宽窗位:", { windowWidthValue, windowLevelValue });
          }
          
          // 更新响应式数据
          windowWidth.value = windowWidthValue;
          windowLevel.value = windowLevelValue;
          initialWindowWidth.value = windowWidthValue;
          initialWindowLevel.value = windowLevelValue;
          
          // 应用到视口
          const lower = windowLevelValue - windowWidthValue / 2;
          const upper = windowLevelValue + windowWidthValue / 2;
          
          viewport.value.setProperties({
            voiRange: { lower, upper }
          });
          
          console.log("窗宽窗位设置完成:", { lower, upper });
        } catch (windowError) {
          console.warn("设置窗宽窗位失败，使用默认值:", windowError);
          // 使用默认值
          windowWidth.value = 400;
          windowLevel.value = 40;
        }
        
        // 强制渲染
        viewport.value.render();
        console.log("视口渲染完成");
        
        // 检查渲染结果
        setTimeout(() => {
          const canvas = viewportElement.querySelector('canvas');
          if (canvas) {
            console.log("Canvas创建成功，尺寸:", canvas.width, "x", canvas.height);
            
            // 如果canvas尺寸为0，强制重新渲染
            if (canvas.width === 0 || canvas.height === 0) {
              console.warn("Canvas尺寸为0，强制重新渲染");
              viewport.value.render();
            }
          } else {
            console.error("Canvas元素未创建");
          }
        }, 500);
      }, 100);

      // 触发imagesLoaded事件
      emit('imagesLoaded', data);
      console.log("DicomViewer图像加载流程完成");

    } else {
      console.warn("DicomViewer: 未接收到有效的图像数据");
    }
  } catch (error) {
    console.error("DicomViewer渲染图像失败:", error);
  }
}

// 添加清理函数
async function cleanupRenderingEngines() {
  console.log("清理渲染引擎...");
  
  // 清理除主引擎外的所有渲染引擎
  const enginesToDestroy = [];
  
  for (const engineId of activeRenderingEngines) {
    if (engineId !== "MAIN_VIEWER_ENGINE") {
      enginesToDestroy.push(engineId);
    }
  }
  
  for (const engineId of enginesToDestroy) {
    try {
      const engine = getRenderingEngine(engineId);
      if (engine) {
        engine.destroy();
        console.log("销毁渲染引擎:", engineId);
      }
      activeRenderingEngines.delete(engineId);
    } catch (error) {
      console.warn("销毁渲染引擎失败:", engineId, error);
    }
  }
  
  // 强制垃圾回收提示（实际效果有限，但可以提醒浏览器）
  if (window.gc) {
    window.gc();
  }
}

// 概览canvas初始化
function initOverviewCanvas() {
  if (!overviewCanvasRef.value) return;
  
  const canvas = overviewCanvasRef.value;
  const ctx = canvas.getContext('2d');
  
  // 设置canvas样式
  ctx.fillStyle = '#000';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // 添加加载提示
  ctx.fillStyle = '#fff';
  ctx.font = '14px Arial';
  ctx.textAlign = 'center';
  ctx.fillText('概览加载中...', canvas.width / 2, canvas.height / 2);
}

// 更新概览canvas
function updateOverviewCanvas() {
  if (!viewport.value || !overviewCanvasRef.value) return;
  
  try {
    const canvas = overviewCanvasRef.value;
    const ctx = canvas.getContext('2d');
    
    // 获取当前图像数据
    const renderingEngine = viewport.value.getRenderingEngine();
    const viewportCanvas = viewport.value.getCanvas();
    
    if (!viewportCanvas) return;
    
    // 清空canvas
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 计算缩放比例，保持宽高比
    const sourceWidth = viewportCanvas.width;
    const sourceHeight = viewportCanvas.height;
    const targetWidth = canvas.width;
    const targetHeight = canvas.height;
    
    const scaleX = targetWidth / sourceWidth;
    const scaleY = targetHeight / sourceHeight;
    const scale = Math.min(scaleX, scaleY);
    
    const scaledWidth = sourceWidth * scale;
    const scaledHeight = sourceHeight * scale;
    const offsetX = (targetWidth - scaledWidth) / 2;
    const offsetY = (targetHeight - scaledHeight) / 2;
    
    // 绘制缩放后的图像
    ctx.drawImage(
      viewportCanvas,
      0, 0, sourceWidth, sourceHeight,
      offsetX, offsetY, scaledWidth, scaledHeight
    );
    
  } catch (error) {
    console.error('更新概览canvas失败:', error);
    // 显示错误信息
    const ctx = overviewCanvasRef.value.getContext('2d');
    ctx.fillStyle = '#333';
    ctx.fillRect(0, 0, overviewCanvasRef.value.width, overviewCanvasRef.value.height);
    ctx.fillStyle = '#fff';
    ctx.font = '12px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('概览加载失败', overviewCanvasRef.value.width / 2, overviewCanvasRef.value.height / 2);
  }
}

// 切片变化处理
function onSliceChange(value) {
  console.log('切片滑动条变化:', value);
  if (!viewport.value) {
    console.error('viewport未初始化，无法切换切片');
    return;
  }
  
  try {
    // 更新当前切片索引
    currentSliceIndex.value = value;
    
    // 设置viewport的图像索引
    viewport.value.setImageIdIndex(value);
    viewport.value.render();
    
    // 更新概览canvas
    updateOverviewCanvas();
    
    // 触发imageChange事件
    emit('imageChange', { currentIndex: value });
    
    console.log('切片切换完成，当前索引:', value);
  } catch (error) {
    console.error('切片切换失败:', error);
  }
}

// 操作面板功能实现 - 修复版本
function flipHorizontal() {
  console.log('执行镜像操作');
  if (!viewport.value) {
    console.error('viewport未初始化，无法执行镜像操作');
    return;
  }
  
  try {
    // 方法1: 使用viewport的flip方法（推荐）
    if (typeof viewport.value.flip === 'function') {
      viewport.value.flip({ flipHorizontal: true });
      viewport.value.render();
      updateOverviewCanvas();
      console.log('使用viewport.flip方法执行镜像操作完成');
      return;
    }
    
    // 方法2: 使用camera属性修改
    const camera = viewport.value.getCamera();
    console.log('当前camera状态:', camera);
    
    // 切换水平翻转状态
    camera.flipHorizontal = !camera.flipHorizontal;
    
    viewport.value.setCamera(camera);
    viewport.value.render();
    updateOverviewCanvas();
    
    console.log('镜像操作完成，新的flipHorizontal状态:', camera.flipHorizontal);
  } catch (error) {
    console.error('镜像操作失败:', error);
    
    // 方法3: 备用方案 - 使用变换矩阵
    try {
      const properties = viewport.value.getProperties();
      const currentTransform = properties.displayArea || {};
      
      // 应用水平翻转变换
      const flipTransform = {
        ...currentTransform,
        scaleX: -(currentTransform.scaleX || 1)
      };
      
      viewport.value.setProperties({
        displayArea: flipTransform
      });
      viewport.value.render();
      updateOverviewCanvas();
      
      console.log('使用变换矩阵执行镜像操作完成');
    } catch (fallbackError) {
      console.error('备用镜像方案也失败:', fallbackError);
    }
  }
}

function rotateClockwise() {
  console.log('执行旋转操作');
  if (!viewport.value) {
    console.error('viewport未初始化，无法执行旋转操作');
    ElMessage.error('视口未初始化');
    return;
  }
  
  try {
    // 方法1: 使用setViewPresentation方法（推荐）
    const currentPresentation = viewport.value.getViewPresentation();
    console.log('当前presentation:', currentPresentation);
    
    if (currentPresentation && typeof viewport.value.setViewPresentation === 'function') {
      // 计算新的旋转角度
      const currentRotation = currentPresentation.rotation || 0;
      const newRotation = (currentRotation + 90) % 360;
      
      const newPresentation = {
        ...currentPresentation,
        rotation: newRotation
      };
      
      viewport.value.setViewPresentation(newPresentation);
      viewport.value.render();
      updateOverviewCanvas();
      
      console.log('使用setViewPresentation完成旋转，角度:', newRotation);
      ElMessage.success(`图像已旋转至${newRotation}度`);
      return;
    }
    
    // 方法2: 使用相机变换（备用方案）
    const camera = viewport.value.getCamera();
    console.log('当前camera:', camera);
    
    if (camera && camera.viewPlaneNormal && camera.viewUp) {
      // 创建旋转矩阵（90度顺时针旋转）
      const viewPlaneNormal = [...camera.viewPlaneNormal];
      const viewUp = [...camera.viewUp];
      
      // 计算右向量
      const viewRight = [
        viewUp[1] * viewPlaneNormal[2] - viewUp[2] * viewPlaneNormal[1],
        viewUp[2] * viewPlaneNormal[0] - viewUp[0] * viewPlaneNormal[2],
        viewUp[0] * viewPlaneNormal[1] - viewUp[1] * viewPlaneNormal[0]
      ];
      
      // 90度旋转：新的viewUp = -viewRight
      const newViewUp = [-viewRight[0], -viewRight[1], -viewRight[2]];
      
      const newCamera = {
        ...camera,
        viewUp: newViewUp
      };
      
      viewport.value.setCamera(newCamera);
      viewport.value.render();
      updateOverviewCanvas();
      
      console.log('使用相机变换完成旋转');
      ElMessage.success('图像已旋转90度');
      return;
    }
    
    // 方法3: 使用CSS变换（最后备用方案）
    const element = viewport.value.getElement();
    if (element) {
      const canvas = element.querySelector('canvas');
      if (canvas) {
        const currentTransform = canvas.style.transform || '';
        const rotateMatch = currentTransform.match(/rotate\((-?\d+)deg\)/);
        const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
        const newRotation = (currentRotation + 90) % 360;
        
        canvas.style.transform = currentTransform.replace(/rotate\(-?\d+deg\)/, '') + ` rotate(${newRotation}deg)`;
        
        console.log('使用CSS变换完成旋转，角度:', newRotation);
        ElMessage.success(`图像已旋转至${newRotation}度`);
        return;
      }
    }
    
    throw new Error('所有旋转方法都不可用');
    
  } catch (error) {
    console.error('旋转操作失败:', error);
    ElMessage.error('旋转功能暂时不可用: ' + error.message);
  }
}

function resetView() {
  console.log('执行重置视图操作');
  if (!viewport.value) {
    console.error('viewport未初始化，无法执行重置操作');
    return;
  }
  
  try {
    // 重置相机
    viewport.value.resetCamera();
    viewport.value.render();
    updateOverviewCanvas();
    
    // 重置调窗参数到初始值
    windowWidth.value = initialWindowWidth.value;
    windowLevel.value = initialWindowLevel.value;
    
    // 应用初始调窗参数
    const lower = windowLevel.value - windowWidth.value / 2;
    const upper = windowLevel.value + windowWidth.value / 2;
    
    viewport.value.setProperties({
      voiRange: { lower, upper }
    });
    viewport.value.render();
    
    console.log('重置视图完成，调窗参数恢复到初始值:', {
      windowWidth: windowWidth.value,
      windowLevel: windowLevel.value
    });
  } catch (error) {
    console.error('重置视图失败:', error);
  }
}

function onWindowingChange() {
  if (!viewport.value) return;
  
  const lower = windowLevel.value - windowWidth.value / 2;
  const upper = windowLevel.value + windowWidth.value / 2;
  
  viewport.value.setProperties({
    voiRange: { lower, upper }
  });
  viewport.value.render();
}


// 新增：垂直图像切换方法 - 供DicomHierarchyView调用
function changeVerticalImage(index) {
  console.log('垂直图像切换请求:', index);
  
  if (!viewport.value) {
    console.error('viewport未初始化，无法切换图像');
    return;
  }
  
  if (typeof index !== 'number' || index < 0) {
    console.error('无效的图像索引:', index);
    return;
  }
  
  try {
    // 调用现有的切片变化处理方法
    onSliceChange(index);
    console.log('垂直图像切换完成，索引:', index);
  } catch (error) {
    console.error('垂直图像切换失败:', error);
  }
}

// 暴露方法供父组件调用
defineExpose({
  changeVerticalImage,
  onSliceChange,
  resetView,
  rotateClockwise
});

</script>

<style scoped>
.dicom-viewer-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 12px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  flex-wrap: wrap;
}

.toolbar-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.group-label {
  font-size: 13px;
  font-weight: 600;
  color: #555;
  white-space: nowrap;
}

.windowing-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.windowing-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.windowing-value {
  font-size: 12px;
  color: #666;
  font-weight: 500;
  min-width: 40px;
  text-align: center;
}

.windowing-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
  white-space: nowrap;
}

.slice-info {
  font-size: 13px;
  color: #666;
  font-weight: 500;
  background: #e9ecef;
  padding: 4px 8px;
  border-radius: 4px;
}

.dicom-viewport {
  flex: 1;
  background: #000;
  position: relative;
  min-height: 500px;
  width: 100%;
  height: 100%;
}

.dicom-viewport canvas {
  width: 100% !important;
  height: 100% !important;
  display: block !important;
}

.overview-section {
  position: absolute;
  top: 80px;
  right: 20px;
  z-index: 10;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 8px;
  padding: 10px;
}

.overview-canvas {
  display: block;
  border: 2px solid #409eff;
  border-radius: 4px;
  cursor: crosshair;
}

.slice-slider-container {
  padding: 10px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e0e0e0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .toolbar-group {
    gap: 6px;
  }
}
</style>